/**
 * 用户状态管理模块
 */
import { login as loginApi, getUserInfo as getUserInfoApi, logout as logoutApi } from '@/api/user'
import md5 from '@/utils/md5'

// Token存储key，与后端和request.js保持一致
const TOKEN_KEY = 'ss_satoken'

const state = {
  token: uni.getStorageSync(TOKEN_KEY) || '',
  userInfo: uni.getStorageSync('userInfo') || null
}

const mutations = {
  SET_TOKEN(state, token) {
    state.token = token
    uni.setStorageSync(TOKEN_KEY, token)
  },
  
  SET_USER_INFO(state, userInfo) {
    state.userInfo = userInfo
    uni.setStorageSync('userInfo', userInfo)
  },
  
  SET_OPENID(state, openid) {
    if (!state.userInfo) {
      state.userInfo = {}
    }
    state.userInfo.openid = openid
    uni.setStorageSync('userInfo', state.userInfo)
  },
  
  CLEAR_USER(state) {
    state.token = ''
    state.userInfo = null
    uni.removeStorageSync(TOKEN_KEY)
    uni.removeStorageSync('userInfo')
  }
}

const actions = {
  /**
   * 用户登录
   */
  async login({ commit }, { phone, password }) {
    try {
      // MD5加密密码
      const encryptedPassword = md5(password)
      
      // loginApi 返回的已经是 data，不需要再 .data
      const data = await loginApi({
        phone,
        password: encryptedPassword
      })
      
      const { token } = data
      
      // 保存token
      commit('SET_TOKEN', token)
      
      return data
    } catch (error) {
      throw error
    }
  },
  
  /**
   * 获取用户信息
   */
  async getUserInfo({ commit }) {
    try {
      // getUserInfoApi 返回的已经是 data，不需要再 .data
      const userInfo = await getUserInfoApi()
      
      // 保存用户信息
      commit('SET_USER_INFO', userInfo)
      
      return userInfo
    } catch (error) {
      throw error
    }
  },
  
  /**
   * 退出登录
   */
  async logout({ commit }) {
    try {
      await logoutApi()
      
      // 清除用户信息
      commit('CLEAR_USER')
    } catch (error) {
      // 即使接口失败也清除本地信息
      commit('CLEAR_USER')
    }
  }
}

const getters = {
  isLoggedIn: state => !!state.token,
  userInfo: state => state.userInfo,
  token: state => state.token,
  openid: state => state.userInfo?.openid || '', // 获取openid
  userType: state => state.userInfo?.userType || 1, // 1-普通用户，3-商家（单商户模式，无配送员）
  isMerchant: state => state.userInfo?.userType === 3 // 是否是商家
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}

